package com.shark.security.jwt.security.model;

import com.shark.security.jwt.persistent.entity.PermissionInfoEntity;
import com.shark.security.jwt.persistent.entity.UserEntity;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

import java.util.ArrayList;
import java.util.List;

public class JwtUserFactory {

    private JwtUserFactory() {

    }

    public static JwtUser createJwtUser(UserEntity user, List<PermissionInfoEntity> listPermission) {
        return new JwtUser(user.getId(), user.getLoginName(), user.getPassword(), mapToGrantedAuthorities(listPermission));
    }

    private static List<MyGrantedAuthority> mapToGrantedAuthorities(final List<PermissionInfoEntity> listPermission) {
        final List<MyGrantedAuthority> list = new ArrayList<>();
        Observable.create(new ObservableOnSubscribe<PermissionInfoEntity>() {

            @Override
            public void subscribe(ObservableEmitter<PermissionInfoEntity> e) throws Exception {
                for (PermissionInfoEntity entity : listPermission) {
                    e.onNext(entity);
                }
                e.onComplete();
            }
        }).map(new Function<PermissionInfoEntity, MyGrantedAuthority>() {
            @Override
            public MyGrantedAuthority apply(PermissionInfoEntity p) throws Exception {
                return new MyGrantedAuthority(p.getUrl(), p.getMethod(), p.getPermission());
            }
        }).subscribe(
                new Consumer<MyGrantedAuthority>() {
                    @Override
                    public void accept(MyGrantedAuthority myGrantedAuthority) throws Exception {
                        list.add(myGrantedAuthority);
                    }
                }
        );
//        for (PermissionInfoEntity p : listPermission) {
//            list.add(new MyGrantedAuthority(p.getUrl(), p.getMethod()));
//        }
        return list;
    }
}
